package cur.nature.framework.core.log;

import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class ClassConverter extends ClassicConverter {
    private static final String FQCN = LOG.class.getName();
    @Override
    public String convert(ILoggingEvent event) {
        StackTraceElement el = this.getTraceElement(new Throwable().getStackTrace());
        if(null != el){
            final String className = el.getClassName();
            int lastIndex = className.lastIndexOf('.');
            return lastIndex != -1 ? className.substring(lastIndex + 1) : className;
        } else {
            final String className = event.getLoggerName();
            int lastIndex = className.lastIndexOf('.');
            return lastIndex != -1 ? className.substring(lastIndex + 1) : className;
        }
    }

//    public String convert(ILoggingEvent event) {
//        //可以在里面增加其他处理，此处return的字符串就是日志输出的最终内容
////        System.out.println("converter1----------------"+event.getLoggerName());
////        System.out.println("converter2----------------"+event.getFormattedMessage());
////        System.out.println("converter3----------------"+event.hasCallerData());
//        StackTraceElement el = this.getTraceElement(new Throwable().getStackTrace());
////        if(el == null){return event.getFormattedMessage();}
////        else{return event.getLoggerName();}
//
//        if(null != el){return el.getClassName();}
//        return event.getLoggerName();
//    }

//    private StackTraceElement getTraceElement(String class1) {
//        StackTraceElement[] steArray = new Throwable().getStackTrace();
//        StackTraceElement res = null;
//        int i;
////        for (;i<aSteArray.StackTraceElement aSteArray : steArray) {
//        for (i=0;i<steArray.length;i++) {
//            if (FQCN.equals(steArray[i].getClassName())) { break;}
//        }
//
//        return steArray[i+1];
//    }

    private StackTraceElement getTraceElement(StackTraceElement[] steArray) {
        StackTraceElement res = null;
        for (int i=0;i<steArray.length;i++) {
            if (FQCN.equals(steArray[i].getClassName())) { res = steArray[i+1];break;}
        }
        return res;
    }
}
